# -*- coding: utf-8 -*-
from __future__ import unicode_literals

import json

from django.db import models
from wenlincms.core.models import Ownable
from wenlincms.utils.models import get_user_model

from wlapps.accounts.models import UCenter
from wlmodels.codes.models import EntIdable
from wlmodels.company.models import ELPost
from wlviews.saas.fee import saas_item_name, statistic_pindao_dict

User = get_user_model()


# 客户消费记录
class ELFeeLog(models.Model):
    customer = models.ForeignKey(User, verbose_name='客户', db_column='customer_id',
                                 related_name='fee_log', null=True, )
    item = models.CharField('消费项', choices=saas_item_name, max_length=2, null=True, blank=True, db_index=True)
    tkey = models.CharField('消费项key', max_length=75, null=True, blank=True, db_index=True,
                            help_text='记录消费项目的关键词，如报告的id')
    count = models.SmallIntegerField("消费条数", null=True, blank=True, default=1)
    fee = models.DecimalField("消费金额", null=True, blank=True, max_digits=15, decimal_places=2)
    ip = models.IPAddressField("访问ip", null=True, blank=True)
    created = models.DateTimeField("消费时间", null=True, auto_now=True)

    class Meta:
        verbose_name = '客户消费记录'
        verbose_name_plural = '客户消费记录'
        db_table = 'el_ucenter_feelog'

    def __unicode__(self):
        return u'%s-消费-%s' % (self.customer, self.pk)

    def save(self, *args, **kwargs):
        # 消费后为客户修改余额
        if not self.created and self.customer and self.fee and self.fee > 0:
            new_yue = float(self.customer.u_ucenter.yue) - float(self.fee)
            UCenter.objects.filter(userid=self.customer).update(yue=new_yue)
        super(ELFeeLog, self).save(*args, **kwargs)

    # 消费项描述
    def _tkey_des(self):
        if self.item and self.item[0] == "1":
            the_post = ELPost.objects.filter(entid=self.tkey).first()
            if the_post:
                return "<a href='%s?version=%s' target='_blank'>%s</a>" % (the_post.get_report_url(), self.item, the_post.ENTNAME)
        elif self.item and self.item[0] == "7":
            try:
                return statistic_pindao_dict[json.loads(self.tkey)["page"]]
            except:
                pass
        elif self.item in ["30", "31", ] and self.tkey[0] == "e":
            the_post = ELPost.objects.filter(entid=self.tkey[1:]).first()
            if the_post:
                return the_post.ENTNAME
        elif self.item in ["51", ]:
            the_post = ELPost.objects.filter(entid=self.tkey).first()
            if the_post:
                return the_post.ENTNAME
        return ""

    _tkey_des.short_description = "消费项描述"

    tkey_des = property(_tkey_des)


# 为客户充值
class ELCustomerCharge(Ownable):
    customer = models.ForeignKey(User, verbose_name='客户', db_column='customer_id',
                                 related_name='customer_charges', null=True, help_text="新建充值记录后不允许修改")
    money = models.DecimalField("充值金额", null=True, max_digits=15, decimal_places=2, help_text="新建充值记录后不允许修改")
    smoney = models.DecimalField("实缴金额", null=True, blank=True, max_digits=15, decimal_places=2, help_text="优惠后实际缴纳的金额")
    beizhu = models.TextField("备注说明", null=True, blank=True)
    created = models.DateTimeField("操作时间", null=True, auto_now=True)

    class Meta:
        verbose_name = '为客户充值'
        verbose_name_plural = '为客户充值'
        db_table = 'el_ucenter_charges'

    def __unicode__(self):
        return u'%s-充值-%s' % (self.customer, self.money)

    def save(self, *args, **kwargs):
        # 充值后为客户修改余额
        if not self.created and self.customer and self.money and self.money > 0:
            new_yue = float(self.customer.u_ucenter.yue) + float(self.money)
            UCenter.objects.filter(userid=self.customer).update(yue=new_yue)
        super(ELCustomerCharge, self).save(*args, **kwargs)


# 客户充值的记录
class ELCustomerChargeLog(ELCustomerCharge):
    class Meta:
        verbose_name = '客户充值记录'
        verbose_name_plural = '客户充值记录'
        proxy = True


# 生命周期参数表
class ELStatisticsLife(models.Model):
    INDUSTRYPHY = models.CharField('行业代码', max_length=4, db_index=True)
    DOMDISTRICT_id = models.CharField('地区代码', db_column='DOMDISTRICT', max_length=6, null=True, blank=True, db_index=True)
    REGCAP = models.FloatField('注册资金', null=True, blank=True, choices=(('1', '1-100'), ('2', '100-1000'), ('3', '1000-')))
    life_k = models.FloatField('k值', null=True, blank=True)
    life_r = models.FloatField('r值', null=True, blank=True)
    method = models.CharField('算法', max_length=10, null=True, blank=True)

    class Meta:
        verbose_name = '生命周期参数'
        verbose_name_plural = '生命周期参数'
        db_table = 'statistics_life'
        app_label = "dataplus"

    def __unicode__(self):
        return u'%s生命周期' % self.INDUSTRYPHY


# SAAS系统公告信息
class ELSaasMsg(Ownable):
    title = models.CharField('公告标题', max_length=200, null=True)
    content = models.TextField("公告内容", null=True)
    url = models.URLField("外部链接", null=True, blank=True)
    created = models.DateTimeField("发布时间", null=True, auto_now=True)

    class Meta:
        verbose_name = 'SAAS公告'
        verbose_name_plural = 'SAAS公告'
        db_table = 'el_ucenter_saasmsg'

    def __unicode__(self):
        return u'SAAS公告-%s' % self.id


# 我的监控
class ELMonitor(EntIdable):
    customer = models.ForeignKey(User, verbose_name='客户', db_column='customer_id',
                                 related_name='u_monitor', null=True)
    created = models.DateTimeField("新增时间", null=True, auto_now=True)

    class Meta:
        verbose_name = '风险监控表'
        verbose_name_plural = '风险监控表'
        db_table = 'el_ucenter_monitor'

    def __unicode__(self):
        return u'%s-监控-%s' % (self.customer, self.pk)


# 风险预警消息
class ELRiskMsg(EntIdable):
    title = models.CharField('消息标题', max_length=200, null=True)
    content = models.TextField("消息内容", null=True)
    created = models.DateTimeField("发布时间", null=True, auto_now=True)

    class Meta:
        verbose_name = '风险预警消息'
        verbose_name_plural = '风险预警消息'
        db_table = 'el_ucenter_riskmsg'

    def __unicode__(self):
        return u'风险预警消息-%s' % self.id
